﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using CsvHelper;
using CsvHelper.Configuration;

namespace Solution.Application.Utils
{
    public class CsvHelper
    {
        private static readonly CsvConfiguration _csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            HasHeaderRecord = true,
            Encoding = Encoding.UTF8
        };

        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="rows">A list of text content to be written, separated by commas</param>
        /// <param name="path"></param>
        /// <param name="append"></param>
        public static void WriteCsv(string fileName, IEnumerable<string> rows, string path = "", bool append = true)
        {
            if (rows == null || !rows.Any())
            {
                return;
            }

            var directory = GetOrCreateDirectory(path);
            using (var writer = new StreamWriter($"{directory}/{fileName}.csv", append))
            {
                using (var cw = new CsvWriter(writer, _csvConfig))
                {
                    foreach (var item in rows)
                    {
                        var fields = item.Split(",");
                        foreach (var field in fields)
                        {
                            cw.WriteField(field);
                        }
                        cw.NextRecord();
                    }
                }
            }
        }

        public static void WriteCsv<T>(string fileName, IEnumerable<T> rows, string path = "", bool append = true)
        {
            if (rows == null || !rows.Any())
            {
                return;
            }

            var directory = GetOrCreateDirectory(path);
            using (var writer = new StreamWriter($"{directory}/{fileName}.csv", append))
            {
                using (var cw = new CsvWriter(writer, _csvConfig))
                {
                    cw.WriteRecords(rows);
                }
            }
        }

        public static List<T> ReadCsv<T>(string fileName)
        {
            var path = GetOrCreateDirectory();
            var directory = $"{path}/{fileName}.csv";
            if (!File.Exists(directory))
            {
                return default;
            }

            List<T> res = default;
            using (var reader = new StreamReader(directory, Encoding.UTF8))
            {
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    var rows = csv.GetRecords<T>();
                    if (rows != null && rows.Any())
                    {
                        res = rows.ToList();
                    }
                }
            }
            return res;
        }

        private static string GetOrCreateDirectory(string path = "")
        {
            if (string.IsNullOrEmpty(path))
            {
                path = Path.Combine(Environment.CurrentDirectory, "output");
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            return path;
        }
    }
}